package Chat_program_Rasmus;

import java.net.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class Client implements Runnable 
{
	// Globals
	
	Socket SOCK;
	Scanner INPUT;
	Scanner SEND = new Scanner(System.in);
	PrintWriter OUT;
	
	// to display time
	private static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

//--------------------------------------------------------
	
	public Client(Socket X)
	{
		this.SOCK = X;
	}
	
//--------------------------------------------------------
	
	public void run()
	{
		try
		{
			try
			{
				INPUT = new Scanner(SOCK.getInputStream());
				OUT = new PrintWriter(SOCK.getOutputStream());
				OUT.flush();
				CheckStream();
			}
			finally
			{
				SOCK.close();
			}
		}
		catch(Exception X)
		{
			System.out.println(X);
		}
	}

//---------------------------------------------------------
	
	public void DISCONNECT() throws IOException
	{
		OUT.println(Client_GUI.UserName + " has disconnected.");
		OUT.println("CLOSE**");
		OUT.flush();
		SOCK.close();
		JOptionPane.showMessageDialog(null, sdf.format(new Date())+" : Bye Bye, "+ Client_GUI.UserName+", you have been disconnected");
	}

//---------------------------------------------------------
	
	public void CheckStream()
	{
		while(true)
		{
			RECEIVE();
		}
	}
//-------------------------------------------------------------------
	
	public void RECEIVE()
	{
		if(INPUT.hasNext()){
			
			String MESSAGE = INPUT.nextLine();
			
			if(MESSAGE.contains("#?!"))
			{
				String TEMP1 = MESSAGE.substring(3);
				TEMP1 = TEMP1.replace("[","");
				TEMP1 = TEMP1.replace("]","");
				
				String[] CurrentUsers = TEMP1.split(", ");
				
				Client_GUI.JL_ONLINE.setListData(CurrentUsers);
			}

			else
			{
				Client_GUI.TA_CONVERSATION.append(sdf.format(new Date())+" :"+MESSAGE + "\n");
			}
		}	
	}

//-------------------------------------------------------------------
	
	public void SEND(String X)
	{
		OUT.println(Client_GUI.UserName + " said: "+X);
		OUT.flush();
		Client_GUI.TF_Message.setText("");
	}

}
